package com.mini.service;

import com.alibaba.fastjson.JSONObject;
import com.mini.conditon.BusinessChanceMaxSetCondition;
import com.mini.model.BusinessChanceMaxSet;
import com.mini.repository.BusinessChanceMaxSetRepository;
import com.mini.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: xiyuefei
 * Date: 2020/12/15
 * Time: 下午5:15
 */

@Slf4j
@Service
public class BusinessChanceMaxSetService  extends BaseService {
    @Autowired
    private BusinessChanceMaxSetRepository businessChanceMaxSetRepository;

    @Autowired
    private MiniAdminService miniAdminService;

    @Autowired
    private InnerOperationRecordService operationRecordService;

    @Autowired
    private BusinessTeacherInfoService teacherInfoService;
    /**
     * 保存分配上限信息
     * @param businessChanceMaxSet
     */
    public void saveBusinessChanceMaxSet(BusinessChanceMaxSet businessChanceMaxSet){
        log.info("saveBusinessChanceMaxSet={}", JSONObject.toJSONString(businessChanceMaxSet));
        List<BusinessChanceMaxSet> relist = businessChanceMaxSetRepository.findByUserId(businessChanceMaxSet.getUserId());
        Date now = new Date();
        StringBuffer logStr = new StringBuffer();
        logStr.append("editUserId="+businessChanceMaxSet.getEditUserId());
        if(relist != null && !relist.isEmpty()){
            businessChanceMaxSet.setId(relist.get(0).getId());
            businessChanceMaxSet.setUpdateTime(now);
            logStr.append(" update userId="+relist.get(0).getId()+" old每日分配的新机会的上限值="+relist.get(0).getChanceEveryDay()+" new 每日分配的新机会的上限值="+businessChanceMaxSet.getChanceEveryDay());
        }else{
            businessChanceMaxSet.setCreateTime(now);
            businessChanceMaxSet.setUpdateTime(now);
            logStr.append(" add userId="+businessChanceMaxSet.getUserId()+" set new 每日分配的新机会的上限值="+businessChanceMaxSet.getChanceEveryDay());
        }
        // 保存操作记录
        try {
            asyncTaskManager.getExecutor().submit(new Runnable() {
                @Override
                public void run() {
                    operationRecordService.addSetMaxLog(businessChanceMaxSet.getEditUserId(), logStr.toString());
                }
            });
        }catch (Exception e){
            log.error("添加设置接待量日志异常",e);
        }
        businessChanceMaxSetRepository.save(businessChanceMaxSet);
        teacherInfoService.updateAddWechatNum(businessChanceMaxSet.getUserId(),businessChanceMaxSet.getChanceEveryDay());
    }

    /**
     * 根据条件查询分配上限
     *
     * @param condition
     * @return
     */
    public List<BusinessChanceMaxSet> businessChanceMaxSetList(BusinessChanceMaxSetCondition condition){
        List<BusinessChanceMaxSet> businessChanceMaxSetList = businessChanceMaxSetRepository.findAll(getBusinessChanceMaxSetSpecification(condition));
        return businessChanceMaxSetList;
    }

    public List<UserVO> getUserListByCondition(BusinessChanceMaxSetCondition condition,String token){
        if(condition.getUserIdList() != null && !condition.getUserIdList().isEmpty()){
            Set<Long> sets = condition.getUserIdList().stream().collect(Collectors.toSet());
           return miniAdminService.batchFindUserList(sets);
        }else {
            Set<Long> queryDeptId = new HashSet<>();
            if(condition.getOgId() != null && condition.getOgId() !=0){
                queryDeptId.add(condition.getOgId());
                List<UserVO> t = miniAdminService.operationUserFilter(token,queryDeptId);
                log.info("param={} result={}",JSONObject.toJSONString(queryDeptId),JSONObject.toJSONString(t));
                return t;
            }else  if(condition.getOdId() != null && condition.getOdId() != 0){
                queryDeptId.add(condition.getOdId());
                List<UserVO> t = miniAdminService.operationUserFilter(token,queryDeptId);
                log.info("param={} result={}",JSONObject.toJSONString(queryDeptId),JSONObject.toJSONString(t));
                return t;
            }else  if(condition.getWorkRoomId() != null && condition.getWorkRoomId() != 0){
                queryDeptId.add(condition.getWorkRoomId());
                List<UserVO> t = miniAdminService.operationUserFilter(token,queryDeptId);
                log.info("param={} result={}",JSONObject.toJSONString(queryDeptId),JSONObject.toJSONString(t));
                return t;
            }else  if(condition.getSkuId() != null && condition.getSkuId() != 0){
                queryDeptId.add(condition.getSkuId());
                List<UserVO> t = miniAdminService.operationUserFilter(token,queryDeptId);
                log.info("param={} result={}",JSONObject.toJSONString(queryDeptId),JSONObject.toJSONString(t));
                return t;
            }else  if(condition.getDepartmentId() != null && condition.getDepartmentId() != 0){
                queryDeptId.add(condition.getDepartmentId());
                List<UserVO> t = miniAdminService.operationUserFilter(token,queryDeptId);
                log.info("param={} result={}",JSONObject.toJSONString(queryDeptId),JSONObject.toJSONString(t));
                return t;
            }else {
//                Long userId = miniAdminService.getLoginUserId(token);
                return miniAdminService.scopedOperationUserList(token);
            }

        }

    }

    private Specification<BusinessChanceMaxSet> getBusinessChanceMaxSetSpecification(BusinessChanceMaxSetCondition condition){
        return new Specification<BusinessChanceMaxSet>() {
            @Override
            public Predicate toPredicate(Root<BusinessChanceMaxSet> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!CollectionUtils.isEmpty(condition.getUserIdList())) {
                    CriteriaBuilder.In<Long> in = criteriaBuilder.in(root.get("userId"));
                    condition.getUserIdList().forEach(o -> in.value(o));
                    predicates.add(in);
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("updateTime")));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }


}
